<template>
  <div id="app" class="lowcode-designer">
    <lowcode-designer ref="vfDesigner" :banned-widgets="testBanned" :designer-config="designerConfig">
      <!-- 自定义按钮插槽演示 -->
      <template #customToolButtons>
        <el-button type="text" @click="$tab.closeOpenPage({path:'/lowcode/lowcode/render/2370409850648662016'})"><i class="el-icon-finished" />关闭</el-button>
        <el-button type="text" @click="saveFormJson"><i class="el-icon-finished" />保存</el-button>
      </template>
    </lowcode-designer>
  </div>
</template>

<script>
import { getPage,updatePage } from "@/api/system/page";
export default {
  name: 'LowcodeDesign',
  mounted(){
    window.addEventListener('keydown', this.handleEvent)
    //获取到路由参数
    let pageId = this.$route.query.pageId;
    this.module = this.$route.query.module;
    if(pageId){
      this.initForm(pageId)
    }else{
      this.$message.warning("未能获取到后台页面数据，已默认展示缓存页面")
    }
  },
  beforeDestroy() {
    window.removeEventListener('keydown', this.handleEvent) // 在页面销毁的时候记得解除
  },
  data() {
    return {
      testBanned: [
      ],
      designerConfig: {},

      module:"",
      currentForm:{},
    }
  },
  methods: {
    //获取页面的json数据
    initForm(pageId){
      let that = this;
      getPage(pageId).then((res) => {
        that.currentForm = res.data;
        if (res.data.pageContent) {
          that.$refs.vfDesigner.setFormJson(JSON.parse(that.unescapeHTML(res.data.pageContent)))
        } else {
          that.$refs.vfDesigner.setFormJson({})
        }
        //设置浏览器标签标题
        document.title = that.module + "-" + res.data.pageName
      }).catch((_) => {})

      this.$refs.vfDesigner.setFormJson({})
    },
    //保存json
    saveFormJson() {
      let formJson = this.$refs.vfDesigner.getFormJson()
      if (formJson.length === 0) {
        this.$message('您还没绘制任何表单内容!')
        return
      }
      this.currentForm.pageContent = JSON.stringify(formJson);
      updatePage(this.currentForm).then(response => {
        if(response.code==200){
          this.$message({
            showClose: true,
            message: '保存成功'
          });
        }else{
          this.$message({
            showClose: true,
            message: response.message
          });
        }
      });
    },
    unescapeHTML(text) {
      return text.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
    },
    //键盘操控监听
    async handleEvent(event) {
      switch (event.keyCode) {
        case 83:
          if(event.ctrlKey){
            event.preventDefault()
            event.returnValue = false // 阻止直接保存网页
            //执行业务逻辑
            this.saveFormJson();
            break
          }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  #app {
    height: 100%;
  }
  #app .main-container {
      margin-left: 0px;
  }
</style>
